package com.mf.common.utils;

import com.google.common.base.Preconditions;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.util.ByteSource;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 加密工具类
 * User: zhaoming
 * Date: 2016-10-12
 * To change this template use File | Settings | File Templates.
 **/
public class EncryptUtils {

    /**
     * 算法名称
     */
    private static final String algorithmName = "MD5";
    /**
     * 私有盐
     */
    private static final String privateSalt = "";
    /**
     * 迭代次数
     */
    private static final Integer iterations = 1;

    /**
     * 不可逆加密
     * @param source 源
     */
    public static String encrypt(String source){
        Preconditions.checkArgument(StringUtils.isNotBlank(source), "source must not be null");

        DefaultHashService hashService = new DefaultHashService(); //默认算法SHA-512
        HashRequest request = new HashRequest.Builder()
                .setAlgorithmName(EncryptUtils.algorithmName)
                .setSource(ByteSource.Util.bytes(source))
                .setSalt(ByteSource.Util.bytes(EncryptUtils.privateSalt))
                .setIterations(EncryptUtils.iterations)
                .build();
        return hashService.computeHash(request).toString();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
        System.out.println(EncryptUtils.encrypt("zhaoming"));
        System.out.println(DigestUtils.md5Hex("zhaoming"));
        System.out.println(DigestUtils.sha1Hex("zhaoming"));
        System.out.println(DigestUtils.sha256Hex("zhaoming"));
        System.out.println(DigestUtils.sha384Hex("zhaoming"));
        System.out.println(DigestUtils.sha512Hex("zhaoming"));
    }
}
